<?php

/**
 * This is the model class for table "tbl_dispatch_tech".
 *
 * The followings are the available columns in table 'tbl_dispatch_tech':
 * @property integer $id
 * @property string $dispatch
 * @property string $counter
 * @property string $empno
 * @property string $status
 * @property string $startdate
 * @property string $starttime
 * @property string $enddate
 * @property string $endtime
 * @property string $mobile
 * @property string $totaltime
 * @property string $worktime
 * @property string $traveltime
 * @property string $complete
 */
class DispatchTech extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return DispatchTech the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_dispatch_tech';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			//array('dispatch, counter, empno, status, startdate, starttime, enddate, mobile, complete', 'required'),
			array('dispatch', 'length', 'max'=>10),
			array('counter, empno', 'length', 'max'=>4),
            array('totaltime, worktime, traveltime','numerical'),
			array('status,switchToStatus', 'length', 'max'=>150),
            array('status','exist','className'=>'Statuscode','attributeName'=>'statuscode'),
			array('mobile, complete', 'length', 'max'=>1),
			
			array('endtime', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, dispatch, counter, empno, status, startdate, starttime, enddate, endtime, mobile, totaltime, worktime, traveltime, complete', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                    
                    'statuscode'=>array(self::BELONGS_TO,'Statuscode','status'),
                    'dispatchModel'=>array(self::BELONGS_TO,'Dispatchdetails','dispatch'),
                    'employee'=>array(self::BELONGS_TO,'Employees','empno')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'dispatch' => 'Dispatch',
			'counter' => 'Counter',
			'empno' => 'Empno',
			'status' => 'Status',
			'startdate' => 'Start Date',
			'starttime' => 'Start Time',
			'enddate' => 'Enddate',
			'endtime' => 'Endtime',
			'mobile' => 'Mobile',
			'totaltime' => 'Totaltime',
			'worktime' => 'Worktime',
			'traveltime' => 'Traveltime',
			'complete' => 'Complete',
		);
	}

        public function init() {
            parent::init();
            $this->totaltime=0;
            $this->traveltime=0;
            $this->worktime=0;
        }
        public function beforeSave() {
            if($this->isNewRecord){
                $num=Yii::app()->db->createCommand('select max(counter) from tbl_dispatch_tech where dispatch=:dispatch')->bindValue('dispatch',$this->dispatch)->queryScalar();
                if(empty($num)){
                    $num=0;
                }
                $this->counter=str_pad($num+1, 3, '0', STR_PAD_LEFT);
            }
            return parent::beforeSave();
        }
        public function changeStatus($newStatus,$empno=null,$date=NULL,$time=NULL,$sentFromIphone = false){
            if($date==NULL) $date=DateUtil::getDefaultCurrentDateTime();
            if($time==NULL) $time=DateUtil::getDefaultCurrentTime();
            $status=Statuscode::model()->findByPk($newStatus);
            /* @var $status Statuscode */
         
            if($status==NULL) return false;
            if($this->dispatchModel->isComplete()){
                return true;
            }
            if($newStatus==$this->status){
                return true;
            }
            
            $this->enddate  = $date;
            $this->endtime  = $time;
            $this->complete = 'Y';
            ///get minutes different
            $fromTime=strtotime($this->startdate.' '.$this->starttime);
            if(strlen($date)>10){
                $toTime = strtotime($date);
            }else{
                $toTime = strtotime($date.' '.$time);
            }            
            $this->totaltime        = round(abs($toTime - $fromTime)/60);
            $this->switchToStatus   = $newStatus;
       
          
            $model              = new DispatchTech;
            $model->dispatch    = $this->dispatch;                            
            $model->startdate   = $date;
            $model->starttime   = $time;
            $model->complete    = 'N';              
            $model->empno       = $this->empno;
            $noSaveNewModel     = false;
            switch($newStatus){
                case 'IT':
                    $model->status = $newStatus;
                    $model->mobile = 0;
                    $model->empno = $empno;
                    if($sentFromIphone){
                        $model->mobile = 1;
                    }
                break;
                case 'Unassigned':
                    $model->empno = $empno;
                    $model->status = $newStatus;
                    if(! $sentFromIphone){
                        DispatchUtil::sendNoticeEmail($this->dispatch,$empno);    
                    }
                    if($sentFromIphone){
                        $model->mobile = 1;
                    }
                    
                break;
                case 'Pending':                  
                    $model->status = $newStatus;    
                    if($sentFromIphone){
                        $model->mobile = 1;
                    }              
                break;
                case 'Reassign':
                    $model->empno = $empno;
                    $model->status = 'Pending';
                    $model->mobile = 0;
                    if(! $sentFromIphone){
                        DispatchUtil::sendNoticeEmail($this->dispatch,$empno);    
                    }
                    
                break;
                case 'Mobile':
                    $model->status = 'Pending';
                    $model->mobile = 1;
                break;
                case 'Download':
                    
                    $model->mobile=1;
                    $model->status= 'Pending';
                break;
                case 'Traveling':                        
                    $model->status = $newStatus;
                    $model->mobile = 0;
                    if($sentFromIphone){
                        $model->mobile = 1;
                    }
                break;
                case 'Working':
                    $model->mobile = 0;
                    $model->status = 'Working';
                    if($sentFromIphone){
                        $model->mobile = 1;
                    }
                break;
                case 'Need Parts';
                    if($status->transfer == ''){
                        $model->empno = $this->empno;
                        if(! $sentFromIphone){
                            DispatchUtil::sendNoticeEmail($this->dispatch,$empno);    
                        }
                    }else{
                        $model->empno = $status->transfer;    
                    }                    
                    $model->mobile = 0;
                    $model->status = 'Need Parts';
                break;
                case 'Called Customer':
                    $model->mobile = 1;
                    $model->status = $newStatus;
                break;
                case 'Acknowledged':
                    $model->mobile = 0;
                    $model->status = $newStatus;
                    if($sentFromIphone){
                        $model->mobile = 1;
                    }
                break;
                case 'Off Job':
                    $model->mobile = 0;
                    $model->status = $newStatus;
                    if($sentFromIphone){
                        $model->mobile = 1;
                    }
                break;
                case 'Phone Fix':
                case 'Complete':
                    $this->status = 'Complete';
                    $this->dispatchModel->complete = DateUtil::getDefaultCurrentDateTime();
                    $this->dispatchModel->save();
                    $noSaveNewModel= true;
                break;
            }                    

            if(!$this->save()){
                echo json_encode($this->errors);
            }
            if( ! $noSaveNewModel){
                if(!$model->save()){
                    echo json_encode($this->errors);
                }    
            }
            
            

          
            return true;
           
        }
}